use std::io::{BufRead, Seek};

pub fn converter(input: &str) -> String {
    // let input = "川普";
    let input = converter_to_simple(input, "t2s").expect("文件格式错误");
    converter_inner(&input).expect("文件格式错误")
}

pub fn converter_inner(input: &str) -> anyhow::Result<String> {
    let mut ret = String::default();
    let wade_file = std::fs::File::open("./wei.txt")?;
    let pinyin_file = std::fs::File::open("./pinyin_utf8.txt")?;
    let mut first = true;
    for c in input.chars() {
        if is_chinese_letter(c) {
            let mut reader = std::io::BufReader::new(&pinyin_file);
            reader.seek(std::io::SeekFrom::Start(0))?;
            for l in reader.lines() {
                let line = l?;
                let arrs = line.split('=').collect::<Vec<_>>();
                if arrs.len() != 2 {
                    return Err(anyhow::anyhow!("文件错误"));
                }
                if arrs[0].chars().next().ok_or(anyhow::anyhow!("文件错误"))? == c {
                    if arrs[1].is_empty() {
                        return Err(anyhow::anyhow!("文件格式错误"));
                    }
                    let reader = std::io::BufReader::new(&wade_file);
                    let mut wade = pinyin_to_wade(arrs[1], reader)?;
                    if first {
                        // 首字母大写
                        let (len, ptr, cap) =
                            unsafe { std::mem::transmute::<_, (usize, *mut u8, usize)>(wade) };
                        unsafe {
                            *ptr -= 32;
                        }
                        wade = unsafe { String::from_raw_parts(ptr, len, cap) };
                        first = false;
                    }
                    ret.push_str(&wade);
                    ret.push(' ');
                }
            }
        }
    }
    Ok(ret.trim().to_owned())
}

// 转换成简体的
fn converter_to_simple(input: &str, tp: &str) -> anyhow::Result<String> {
    let file = std::fs::File::open("./STPhrases.txt")?;
    let reader = std::io::BufReader::new(file);
    for line in reader.lines() {
        let line = line?;
        let key_value = line.split("\t").collect::<Vec<_>>();
        if key_value.len() != 2 {
            continue;
        }
        if tp == "s2t" {
            if key_value[0] == input {
                return Ok(key_value[1].to_owned());
            }
        }

        if tp == "t2s" {
            if key_value[1] == input {
                return Ok(key_value[0].to_owned());
            }
        }
    }
    Ok(input.to_owned())
}

/// 拼音转换成威妥玛
pub fn pinyin_to_wade(
    pinyin: &str,
    mut reader: std::io::BufReader<&std::fs::File>,
) -> anyhow::Result<String> {
    reader.seek(std::io::SeekFrom::Start(0))?;
    for l in reader.lines() {
        let line = l?;
        let key_value = line.split('=').collect::<Vec<_>>();
        if key_value.len() != 2 {
            return Err(anyhow::anyhow!("文件格式错误"));
        }
        if key_value[0] == pinyin {
            return Ok(key_value[1].to_owned());
        }
    }
    Ok(pinyin.to_owned())
}

#[inline(always)]
pub fn is_chinese_letter(ch: char) -> bool {
    if ch as usize >= 0x4E00 && ch as usize <= 0x9FA5 {
        true
    } else {
        false
    }
}
